import requests
import re
import os
import json
'''
1.解析地址，获取找到图片地址https://lol.qq.com/biz/hero/champion.js
2.获取英雄id,及皮肤id（id,name存放在js文件中）
 https://game.gtimg.cn/images/lol/act/img/skin/big2002.jpg
 https://game.gtimg.cn/images/lol/act/img/skin/big2016.jpg
 https://game.gtimg.cn/images/lol/act/img/skin/big20003.jpg
 https://game.gtimg.cn/images/lol/act/img/skin/big39000.jpg
3.爬取图片


'''

def parse_url(url):
    response = requests.get(url)
    code = response.status_code
    responseText = response.text
    return code,responseText

def generaidname(heroiddict):
    for id,name in heroiddict.items():
        yield {"id":id,"name":name}


def download_img(restext,path=r"D:\tensorflow2_pytorch\image"):
    regex = re.compile('champion={"keys":(.*?),"data":',re.S)
    heroid = regex.findall(restext)[0]
    heroiddict = json.loads(heroid)
    idgenra = generaidname(heroiddict)
    if not path:
        os.makedirs(r"D:\tensorflow2_pytorch\image")
    #拼接图片地址并下载
    for dic in idgenra:
       for i in range(16):
           print(dic["name"])
           if len(str(i)) == 1:
               imgpath = "https://game.gtimg.cn/images/lol/act/img/skin/big"+dic["id"]+"00"+str(i)+".jpg"
           else:
               imgpath = "https://game.gtimg.cn/images/lol/act/img/skin/big" + dic["id"] + "0" + str(i) + ".jpg"
           pathfile = path+"\\"+dic["name"]+".jpg"
           recposecont = requests.get(imgpath)
           image = recposecont.content
           if recposecont.status_code == 200:
               with open(pathfile,"wb") as f:
                   f.write(image)
               print("下载结束")
           else:
               continue
if __name__ == '__main__':
    URL = "https://lol.qq.com/biz/hero/champion.js"
    code,restext = parse_url(URL)
    download_img(restext)


